<template>
  <div class="bg home-container">

    <!-- 用户信息 -->
    <div>
      <el-card  style="background-color: rgba(245, 245, 245, 0.5);
    backdrop-filter: blur(5px);
    border: 1px solid rgba(200, 200, 200, 0.5);
    border-radius: 10px;">
        <div style="display: flex; justify-content: space-between; align-items: center; height: 10px">
          <div>欢迎您 {{ user.name }} ，祝您使用愉快</div>
          <div v-if="user.role === '学员' && Number(userUnReadCount) !== 0" style="font-size: 18px; color: red;">
            您有 {{ userUnReadCount }} 条新消息请点击
            <span style="color: #0f9876; cursor: pointer;" @click="$router.push('/message')"> 查看</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 走马灯 -->
    <template>
      <div style="display: flex">
        <div style="width: 70%; margin: 0 auto 0 15%;">
          <el-carousel :interval="5000" type="card" height="250px">
            <el-carousel-item v-for="(item, index) in marquee" :key="index">
              <div style="display: flex; justify-content: space-between; height:250px">
                <div style="width: 5%; writing-mode: vertical-rl; ">{{item.title}}</div>
                <el-image style="width: 95%; height: 100%"
                          :src="item.imgUrl" :preview-src-list="[item.imgUrl]"></el-image>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div v-if="user.role === '管理员'"
             style="width: 15%; display: flex; flex-direction: column; justify-content: center; height: 100%;">
          <el-button type="success" plain @click="addMarqueeDialog()"
                     style="margin: 50px 20px 30px 20px">新增走马灯</el-button>
          <el-button type="warning" plain @click="showMarqueeDialog()"
                     style="margin: 0 20px">编辑走马灯</el-button>
        </div>
      </div>
    </template>

    <div style="display: flex; justify-content: space-between; height: 350px;">
      <!-- 公告栏 -->
      <el-card class="glass-card notice-card" style="width: 49%;  overflow: auto;">
        <div style="margin-bottom: 15px; font-size: 20px; font-weight: bold">系统公告</div>
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item v-for="(item, index) in notices" :key="item.id" :name="index + ''">
            <template slot="title">
              <h4>{{ item.title }}</h4>
            </template>
            <div>{{ item.content }}</div>
            <div style="text-align: right">在 {{ item.time }} 由 {{ item.username }} 发布</div>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <!-- 说明栏 -->
      <el-tabs class="glass-card instruction-card" type="border-card"
               style="width: 49%;  overflow: auto; border-radius: 10px;" stretch="true">
        <el-tab-pane v-for="(item) in instruction" :key="item.id" :label="item.title">
          <div v-if="user.role === '管理员'">
            <el-button type="success" plain @click="handleAdd">新增</el-button>
            <el-button type="primary" plain @click="handleEdit(item)">编辑</el-button>
            <el-button type="danger" plain @click="handleDelete(item.id)">删除</el-button>
          </div>
          <div style="font-size: 16px; color: #333; margin-top: 10px;">{{ item.content }}</div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 说明栏编辑/新增对话框 -->
    <el-dialog title="说明" :visible.sync="instructionDialogVisible" width="30%">
      <el-form :model="instructionForm" label-width="80px"
               style="padding-right: 20px" :rules="instructionRules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="instructionForm.title" @keyup.enter.native="save()"
                    placeholder="请输入标题"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="instructionForm.content" @keyup.enter.native="save()"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="instructionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 跑马灯数据表格 -->
    <el-dialog title="走马灯" :visible.sync="deleteMarqueeVisible" width="70%" style="margin-top:-100px !important;">
      <el-table :data="marquee">
        <el-table-column prop="title" label="标题" width="100px"></el-table-column>
        <el-table-column label="图片预览" width="400px">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: auto; height: 100px;"
                        :src="scope.row.imgUrl"
                        :preview-src-list="[scope.row.imgUrl]">
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="imgUrl" label="图片链接" width="200px"></el-table-column>
        <el-table-column prop="orderNum" label="顺序值（值越大越靠前）" align="center" width="100px"></el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template v-slot="scope">
            <el-button size="mini" type="danger" plain @click="deleteMarquee(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增/编辑跑马灯对话框 -->
    <el-dialog title="走马灯" :visible.sync="addMarqueeVisible" width="50%">
      <el-form :model="marqueeForm" label-width="80px" style="padding-right: 20px" :rules="marqueeRules" ref="marqueeFormRef">
        <div style="margin: 15px; text-align: center">
          <el-upload
              action="http://localhost:9090/file/upload"
              :headers="{ token: this.user.token }"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleMarqueeSuccess">
            <img v-if="marqueeForm.imgUrl" :src="marqueeForm.imgUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <el-form-item label="标题" prop="title">
          <el-input v-model="marqueeForm.title" @keyup.enter.native="save()"
                    placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="顺序值" prop="orderNum">
          <el-input v-model="marqueeForm.orderNum" @keyup.enter.native="save()"
                    placeholder="请输入顺序值（越大越靠前）"></el-input>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="addMarquee">保 存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: "Home",

  // 组件的数据对象
  data() {
    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      notices: [], // 存储系统公告数据
      activeName: '0', // 当前展开的公告项索引
      userUnReadCount: '', // 用户未读消息数量

      instruction: [], // 存储说明栏数据
      instructionDialogVisible: false, // 说明栏位对话框的显示与隐藏
      instructionForm: {}, // 存储表单数据
      instructionRules: { // 表单验证规则
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        content: [{required: true, message: '请输入内容', trigger: 'blur'}],
      },

      deleteMarqueeVisible: false, // 编辑跑马灯对话框的显示与隐藏
      addMarqueeVisible: false, // 新增跑马灯对话框的显示与隐藏
      marquee: [], // 存储跑马灯数据
      marqueeForm: {}, // 存储新增/编辑跑马灯数据
      marqueeRules:{
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        orderNum: [{required: true, message: '请输入顺序值', trigger: 'blur'}],
        imgUrl: [{ required: true, message: '请上传文件', trigger: 'blur' }]
      },
    }
  },

  // 组件创建时调用加载公告和说明栏数据的方法
  created() {
    this.loadNotice()
    this.loadInstruction()
    this.loadMarquee()
  },

  // 组件挂载后调用获取用户未读消息数量的方法
  mounted() {
    this.unReadCountPerUser()
    this.loadUnReadCount(this.user.username)
  },

  methods: {
    showMarqueeDialog() {
      this.deleteMarqueeVisible = true
    },
    addMarqueeDialog() {
      this.marqueeForm = {}
      this.addMarqueeVisible = true
    },
    addMarquee() {
      this.$refs.marqueeFormRef.validate(valid => {
        if (valid && this.marqueeForm.imgUrl) {
          this.$request.post('/marquee/add', this.marqueeForm).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.loadMarquee();
              this.addMarqueeVisible = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error('请填写所有必填字段并上传文件');
        }
      });
    },
    beforeUpload(file) {
      if (!file) {
        this.$message.error('请选择一个文件');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    handleMarqueeSuccess(response, file, fileList) {
      if (response.data && response.data) {
        this.marqueeForm.imgUrl = response.data;
      } else {
        this.$message.error('上传失败，请重试');
      }
    },
    deleteMarquee(id){
      // 弹出确认删除的提示框
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(response => {
        // 发送删除请求
        this.$request.delete('/marquee/delete/' + id).then(res => {
          if (res.code === '200') {   // 操作成功
            this.$message.success('删除成功')
            this.loadMarquee()
          } else {
            this.$message.error(res.msg)  // 弹出错误信息
          }
        })
      }).catch(() => {})
    },

    // 加载系统公告数据的方法
    loadNotice() {
      this.$request.get('/notice/selectOpen').then(res => {
        this.notices = res.data
      })
    },

    // 统计每个用户未读消息数量的方法
    unReadCountPerUser() {
      this.$request.get(`/message/unReadCountPerUser`);
    },

    // 获取用户未读消息数量的方法
    loadUnReadCount() {
      this.$request.get(`/user/getUnRead?username=${this.user.username}`).then(res => {
        this.userUnReadCount = res.data
      })
    },

    // 加载说明栏数据的方法
    loadInstruction() {
      this.$request.get('/instruction/selectAll').then(res => {
        this.instruction = res.data
      })
    },

    // 新增数据方法
    handleAdd() {   // 新增数据
      this.instructionForm = {}
      this.instructionDialogVisible = true   // 打开弹窗
    },

    // 编辑数据方法
    handleEdit(item) {   // 编辑数据
      this.instructionForm = JSON.parse(JSON.stringify(item))  // 给form对象赋值，要深拷贝数据
      this.instructionDialogVisible = true   // 打开弹窗
    },

    // 删除标签页
    handleDelete(id) {
      // 弹出确认删除的提示框
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(() => {
        // 先获取当前数据总数
        this.$request.get('/instruction/count').then(countRes => {
          if (countRes.data <= 1) {  // 如果只剩最后一条
            this.$message.warning('不能删除最后一条数据')
            return
          }

          // 发送删除请求
          this.$request.delete('/instruction/delete/' + id).then(res => {
            if (res.code === '200') {   // 操作成功
              this.$message.success('删除成功')
              this.loadInstruction()
            } else {
              this.$message.error(res.msg)  // 弹出错误信息
            }
          })
        }).catch(err => {
          this.$message.error('获取数据数量失败: ' + err.message)
        })
      }).catch(() => {
        // 用户取消删除
      })
    },
    // 保存数据方法
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 根据是否有id来判断是新增还是更新
          this.$request({
            url: this.instructionForm.id ? '/instruction/update' : '/instruction/add',
            method: this.instructionForm.id ? 'PUT' : 'POST',
            data: this.instructionForm
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.loadInstruction()
              this.instructionDialogVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },

    loadMarquee() {
      this.$request.get('/marquee/selectAll').then(res => {
        // 按orderNum字段降序排序
        this.marquee = res.data.sort((a, b) => b.orderNum - a.orderNum);
      }).catch(error => {
        console.error('加载跑马灯信息失败:', error);
      });
    },
  },

}
</script>


<style>
/* 走马灯 */
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}
.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

/* 公告栏 */
.el-collapse-item__content {
  word-wrap: break-word; /* 允许长单词或 URL 地址换行到下一行 */
  word-break: break-all; /* 强制英文单词断行 */
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
}

/* 深度选择器，用于修改 Element UI 组件内部的样式 */
/deep/.el-form-item__label {
  font-weight: bold; /* 标签字体加粗 */
}

/deep/.el-upload {
  border-radius: 50%; /* 上传组件圆角为 50% */
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9; /* 上传区域边框样式 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
  position: relative; /* 相对定位 */
}

/deep/.avatar-uploader .el-upload:hover {
  border-color: #409EFF; /* 鼠标悬停时边框颜色变化 */
}

/* 头像上传组件的图标样式 */
.avatar-uploader-icon {
  font-size: 28px; /* 图标字体大小 */
  color: #8c939d; /* 图标颜色 */
  width: 178px; /* 图标宽度 */
  height: 178px; /* 图标高度 */
  line-height: 178px; /* 行高，使图标垂直居中 */
  text-align: center; /* 文本居中 */
}

/* 用户头像图片样式 */
.avatar {
  width: 100%; /* 图片宽度 */
  height: 200px; /* 图片高度 */
  display: block; /* 块级元素 */
}

/* 公共毛玻璃卡片样式 */
.glass-card {

  --glass-bg-color: rgba(255, 255, 255, 0.5);
  --glass-blur: 3px;
  --fallback-color: white; /* 新增备用颜色变量 */
  position: relative;
  z-index: 1; /* 确保卡片主体在正常层级 */
}
.glass-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background:
      var(--bg-image) center/cover no-repeat,var(--fallback-color);
  filter: blur(var(--glass-blur));
  z-index: -1;
}
.glass-card::after {
  content: '';
  position: absolute;
  inset: 0;
  background: var(--glass-bg-color);
  z-index: -1;
}

/* 公告毛玻璃卡片背景 */
.notice-card {
  --bg-image: url('@/assets/logo/home-notice.png');
}
/* 说明毛玻璃卡片背景 */
.instruction-card {
  --bg-image: url('@/assets/logo/home-instruction.png');
}

.home-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
  background:
      linear-gradient(rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.3)), /* 白色半透明遮罩让颜色变淡 */
      url('~@/assets/bg/home.png') center 30%/cover no-repeat;
}

.el-tabs:hover{
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease; /* 添加平滑过渡 */
}
</style>